package cn.git.future;

import cn.git.entity.Person;

import java.util.Arrays;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @description: 自定义循环异步调用例子
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-08-07
 */
public class TestDemo {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 设定参数信息，循环多少次也是入参参数
        int [] params = {1,2,3,4,5,6,7,8,9,10};
        CompletableFuture[] futures = IntStream.of(params)
                .mapToObj(param -> {
                    CompletableFuture<Person> future = CompletableFuture.supplyAsync(() -> {
                        if (param == 5) {
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("线程：" + Thread.currentThread().getName() + "正在执行任务：" + param);
                        Person person = new Person();
                        person.setSex("男");
                        person.setAge(param);
                        person.setName("张三");
                        return person;
                    }, executor);
                    return future;
                }).toArray(CompletableFuture[]::new);

        // 等待所有CompletableFuture完成
        CompletableFuture.allOf(futures).join();

        // 获取所有结果
        Object[] results = Stream.of(futures)
                .map(future -> {
                    try {
                        return future.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                        return null;
                    }
                })
                .toArray();

        // 打印结果
        System.out.println(Arrays.stream(results).map(Object::toString).collect(Collectors.joining("\n")));
    }
}
